package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.BehaviorArticleService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ArticleDto;
import com.heima.model.common.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserRelationDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApCollection;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@Service
public class BehaviorArticleServiceImpl implements BehaviorArticleService {

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private ApCollectionMapper apCollectionMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 用户收藏
     *
     * @param dto
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        if (dto == null || dto.getEntryId() == null || dto.getOperation() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取redis key
        Integer userId = ApThreadLocalUtil.get();
        String userEntryId = String.valueOf(userId)+dto.getEntryId();
        String jsonStr = cacheService.get(userEntryId);
        Map<String,Object> map = new HashMap<>();
        //判断是否存在数据
        if (StringUtils.isNotEmpty(jsonStr)){
            //获取数据
            map = JSONObject.parseObject(jsonStr, Map.class);
        }
        //0收藏    1取消收藏
        if (dto.getOperation() == 0){
            //保存app收藏信息表
            ApCollection apCollection = new ApCollection();
            apCollection.setEntryId(Long.valueOf(userId));
            apCollection.setArticleId(apCollection.getArticleId());
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublishedTime());

            apCollectionMapper.insert(apCollection);
        }else if (dto.getOperation() == 1){
            //删除app收藏信息表
            apCollectionMapper.delete(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId,dto.getEntryId()));
        }

        //封装数据
        map.put("collection",dto.getOperation());   //0收藏  1取消收藏
        map.put("publishedTime",dto.getPublishedTime());
        map.put("type",dto.getType());  //0文章  1动态

        //存入redis
        cacheService.set(userEntryId, JSON.toJSONString(map));
        //保存到apArticle表中
        ArticleDto articleDto = new ArticleDto();
        articleDto.setAuthorId(dto.getEntryId());
        articleDto.setLikes(dto.getOperation() == 0 ? 1:-1);
        apArticleService.behaviorArticle(articleDto);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 加载文章行为
     *
     * @param dto
     */
    @Override
    public ResponseResult loadArticleBehavior(UserRelationDto dto) {
        //获取redis key
        Integer userId = ApThreadLocalUtil.get();
        String userArticleId = String.valueOf(userId)+dto.getArticleId();
        String jsonStr = cacheService.get(userArticleId);
        String jStr = cacheService.get(String.valueOf(userId));

        Set set = JSONObject.parseObject(jStr, Set.class);

        Map<String,Object> map = new HashMap<>();
        //初始化data
        Map<String,Object> data = new HashMap<>();
        data.put("islike",false);
        data.put("isunlike",false);
        data.put("iscollection",false);
        data.put("isfollow",false);
        //判断是否关注作者
        if (set != null){
            for (Object o : set) {
                if (dto.getAuthorId().equals((int)o)){
                    data.put("isfollow",true);
                }
            }
        }
        //判断redis是否存在数据
        if (StringUtils.isNotEmpty(jsonStr)){
            //获取数据
            map = JSONObject.parseObject(jsonStr, Map.class);
            Object likeObj = map.get("article");
            //判断是否点赞
            if (likeObj != null) {
                int islike = (int) likeObj;
                data.put("islike", islike == 0);
            }
            Object unlikeObj = map.get("unlike");
            //判断是否喜欢
            if (unlikeObj != null){
                int unlike =(int) unlikeObj;
                data.put("isunlike", unlike == 0);
            }
            Object collectionObj = map.get("collection");
            //判断是否收藏
            if (collectionObj != null){
                int collection = (int) collectionObj;
                data.put("iscollection", collection == 0);
            }

            /*Object followObj = map.get("follow");
            if (followObj != null){
                short follow = (short) followObj;
                data.put("isfollow", follow == 0  );
            }*/

            return ResponseResult.okResult(data);
        }
        //查看数据库数据
        ApCollection apCollection = apCollectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery()
                        .eq(ApCollection::getEntryId, userId)
                        .eq(ApCollection::getArticleId,dto.getArticleId()));

        if (apCollection != null){
            data.put("iscollection",true);
            map.put("collection",0);
        }

        cacheService.set(userArticleId,JSON.toJSONString(map));

        return ResponseResult.okResult(data);
    }
}
